"""Field

 [...]
"""
import itertools

from jinja2 import Template
from jinja2 import Environment, FileSystemLoader

from models import items
from templates.resource_ext_doc import EXTENSIONS
from utils import columnsplit

env = Environment(trim_blocks=True, lstrip_blocks=True, 
                  loader=FileSystemLoader('templates'))


def resourcedoc():
    template = env.get_template('resource.html')

    codes = []
    for item in items:
        title, code = item['title'].split('/')
        tablename = item['tablename']
        columns = columnsplit(item['columns'])

        codes.append(code)

        _columns = [x[0] for x in columns]
        doc = template.render(title=title,
                              code=code,
                              columns=_columns,
                              extensions=EXTENSIONS)

        if 1:
            with open('gen/doc/resource/{}.rst'.format(code), 'w') as f:
                f.write(doc)
        else:
            print(doc)
            return

    template = env.get_template('resource-toctree.html')
    doc = template.render(codes=codes)
    if 1:
        with open('gen/doc/resource.rst', 'w') as f:
            f.write(doc)
    else:
        print(doc)


def linkrelationdoc():
    template = env.get_template('link-relation.html')

    codes = []
    for item in items:
        title, code = item['title'].split('/')
        tablename = item['tablename']
        columns = columnsplit(item['columns'])
        links = item['links']

        codes.append(code)

        _columns = [i[0] for i in columns if 'readonly' not in i[2]]
        doc = template.render(title=title,
                              code=code,
                              links=links,
                              columns=_columns)

        if 1:
            with open('gen/doc/link-relation/{}.rst'.format(code), 'w') as f:
                f.write(doc)
        else:
            print(doc)
            return
        break

    template = env.get_template('link-relation-toctree.html')
    doc = template.render(codes=codes)
    if 1:
        with open('gen/doc/link-relation.rst', 'w') as f:
            f.write(doc)
    else:
        print(doc)


if __name__ == '__main__':
    resourcedoc()
    linkrelationdoc()
